package com.dxjy.demo.module.sys.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.dxjy.demo.config.shiro.JWTUtil;
import com.dxjy.demo.entity.R;
import com.dxjy.demo.entity.ResponseCode;
import com.dxjy.demo.module.sys.entity.SysUser;
import com.dxjy.demo.module.sys.mapper.SysUserMapper;
import com.dxjy.demo.module.sys.redis.RedisKeyEnum;
import com.dxjy.demo.module.sys.redis.StringRedis;
import com.dxjy.demo.utils.IPUtils;
import com.dxjy.demo.utils.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;


@Slf4j
@CrossOrigin
@Api(tags = "登录")
@RestController
@RequestMapping("/base/")
public class LoginController {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private StringRedis stringRedis;


    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public R login(@RequestParam("username") String username,
                   @RequestParam("password") String password,
                   @RequestParam("captcha") String captcha,
                   @RequestParam("captchaId") String captchaId) {
        String value = stringRedis.getValue(RedisKeyEnum.CAPTCHA, captchaId);
        if (StringUtils.isBlank(value)){
            return R.error(ResponseCode.CODE_INVALID);
        }
//        if (!captcha.equalsIgnoreCase(value)) {
//            return R.error(ResponseCode.CODE_ERROR);
//        }
        SysUser user = userMapper.getUserByName(username);
        if (user == null) {
            return R.error(ResponseCode.USER_NOT_EXIST);
        }
        if (user.getStatus() == 3) {
            return R.error(ResponseCode.USER_DISABLE);
        }
        String realPassword = user.getPassword();
        if (realPassword == null) {
            return R.error("用户名错误");
        } else if (!realPassword.equals(MD5Util.md5(password))) {
            return R.error("密码错误");
        }
        JSONObject data = new JSONObject();
        data.put("user", user);
        data.put("token", JWTUtil.createToken(String.valueOf(user.getId())));
        return R.ok(data);
    }


    private JSONObject userFormat(SysUser user) {
        return (JSONObject) JSONObject.parseObject(user.toString()).remove("password");
    }


    /**
     * 重置密码
     */
    @ApiOperation(value = "重置密码")
    @PostMapping(value = "/resetPassword")
    public R resetPassword(@RequestParam Long phone,
                           @RequestParam String password,
                           @RequestParam String code) {
        if (!StringUtils.isNotBlank(code)) {
            return R.error("验证码不能为空！");
        }
//        String realCode = (String)codeRedisDao.getValue(phone);
//        if (code.equalsIgnoreCase(realCode)){
//            boolean b = userMapper.updateUserPassword(MD5Util.md5(password), phone);
//            return b ? new Result().success() : new Result().error("重置失败，请联系管理员！");
//        }
        return R.error("验证码错误！");
    }

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "注册管理员账号")
    @PostMapping(value = "/register", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @RequiresRoles("admin")
    public R doRegister(HttpServletRequest request,
                        @ApiParam(required = true, value = "用户信息，json格式")
                        @RequestBody SysUser user) {
        log.info("+++++++++++++++++doRegister+++++++++++++++++++");
        Long id = user.getId();
        SysUser sysUser = userMapper.getUserByUserId(id);
        // 加密
        String pwd = MD5Util.md5(user.getPassword());
        user.setPassword(pwd);
        if (sysUser != null) {
            try {
                SysUser result = userMapper.getUserByName(user.getUsername());
                if (result != null) {
                    return R.error("该用户名已被使用！");
                }
                user.setRegistDate(new Date());
                user.setLastLoginDate(new Date());
                user.setLastLoginIp(IPUtils.getIpAddr(request));
                user.setRoleId(3);
                userMapper.insertUser(user);
                return R.ok("注册成功！");
            } catch (Exception e) {
                log.error("注册失败", e);
                return R.error("注册失败，请联系网站管理员！");
            }
        }
        return R.ok("success");
    }


    /**
     * 验证码
     *
     * @param response
     * @param request
     */
    @ApiOperation(value = "获取验证码")
    @GetMapping(value = "/captcha")
    public R captcha(HttpServletResponse response, HttpServletRequest request,
                     @RequestParam(defaultValue = "300") int width,
                     @RequestParam(defaultValue = "100") int height) {
        log.info("开始生成验证码…");
        try {
            // 定义图形验证码的长和宽
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(width, height);
            String code = lineCaptcha.getCode();
            // 输出code
            log.info(code);
            // 写出到浏览器（Servlet输出）
//            lineCaptcha.write(response.getOutputStream());
            // 返回JSON
            String uuid = IdUtil.simpleUUID();
            JSONObject result = new JSONObject();
            result.put("captchaId", uuid);
            result.put("picPath", lineCaptcha.getImageBase64Data());
            // 缓存
            stringRedis.setValue(RedisKeyEnum.CAPTCHA, uuid, code);
            return R.ok(result);
        } catch (Exception e) {
            log.error("图形验证码生成失败", e);
        }
        return R.error();
    }

    @GetMapping(path = "/unauthorized/{message}")
    public R unauthorized(@PathVariable String message) {
        if (StringUtils.isNotBlank(message)) {
            if (message.equals(ResponseCode.TOKEN_AUTHENTICATION_FAILED.getMessage())) {
                return R.error(ResponseCode.TOKEN_AUTHENTICATION_FAILED.getCode(), message);
            } else if (message.equals(ResponseCode.USER_NOT_EXIST.getMessage())) {
                return R.error(ResponseCode.USER_NOT_EXIST.getCode(), message);
            } else if (message.equals(ResponseCode.USER_DISABLE.getMessage())) {
                return R.error(ResponseCode.USER_DISABLE.getCode(), message);
            }
        }
        return R.error(message);
    }


}
